import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Block, Picker } from '@tarojs/components'
import { AtBadge } from 'taro-ui'
import http from '@/utils/http';
import utils from '@/utils/util';
import { get as getGlobalData } from '@/global'
import './index.scss'
import StatusPages from '@/components/statusPages/index';
import AutoFormId from "@/components/autoFormId/index";

const app = Taro.getApp();

class Index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      homeObj: {
        countClass: 0,
        countAll: 0,
        countUse: 0,
        countValidity: 0
      },
      wardArr: [],
      isNew: false,
      isScan: false,
      isShowPage: false,
      isVh100: true,
      wardId: '',
      wardObj: {},
      title: '当前未领取药箱',
      statusType: '', // none 不显示空白页  empty //显示空白页
      statuserro: false, // 是否显示错误页
      phone: '400082820',
      memuList: [{
        name: '药箱管理',
        path: '/pages/medicineCabinetManagement/index',
        icon: require('../../assets/imgs/home/home_icon_yxgl.png')
      }, {
        name: '药品管理',
        path: '/pages/drugAdministration/index',
        icon: require('../../assets/imgs/home/home_icon_ypgl.png')
      }, {
        name: '消耗记录',
        path: '/pages/consumptionRecord/index',
        icon: require('../../assets/imgs/home/home_icon_xhjl.png')
      }, {
        name: '巡检',
        path: '/pages/scan/index',
        icon: require('../../assets/imgs/home/home_icon_xj.png')
      }, {
        name: '巡检记录',
        path: '/pages/signRecord/index',
        icon: require('../../assets/imgs/home/home_icon_xjjl.png')
      }, {
        name: '设置',
        path: '/pages/setting/index',
        icon: require('../../assets/imgs/home/home_icon_sz.png')
      }]
    };
  }
  componentWillMount() {
    utils.showLoading();
  }
  componentWillUnmount() { }
  config = {
    navigationBarTitleText: '首页'
  }
  componentDidShow() {
    if (this.state.isScan === false) {
      this.initPage();
    }
    if (Taro.canIUse("getUpdateManager")) {
      const updateManager = Taro.getUpdateManager()
      updateManager.onCheckForUpdate(() => { })
      updateManager.onUpdateReady(function () {
        Taro.showModal({
          title: '张中医急救',
          content: '新版本已经准备好，是否重启应用？',
          success: (res) => {
            if (res.confirm) {
              updateManager.applyUpdate()
            } else {
              this.initPage();
            }
          }
        })
      })
      updateManager.onUpdateFailed(() => { })
    } else { }
  }
  getAllwards() {
    let { wardId } = this.state;
    http.get('getAllwards', {}, false, false, false).then((d) => {
      let wardArr = d.datas;
      let userInfo = getGlobalData('userInfo') || utils.getUserInfo();
      if (userInfo && userInfo.groupid !== 1) {
        wardArr = wardArr.filter(item => userInfo.ward == item.id)
      }
      if (wardArr.length > 0) {
        let flag = false, wardObj = null;
        if (wardId) { // 历史存在
          wardArr.map((item) => {
            if (item.id == wardId) { // 历史选择存在并且能查询出来
              flag = true;
              wardObj = item;
            }
          })
        }
        if (flag === false) {
          wardObj = wardArr[0];
          wardId = wardArr[0].id;
        }
        app.saveSync('lastwardId', wardId);
        this.setState({
          wardObj,
          wardId,
          wardArr
        }, () => {
          this.setState({
            isShowPage: true,
          })
          this.getMedicalkit(wardId)
        })
      } else {
        this.emptyWards();
      }
    }).catch(() => {
      this.emptyWards();
    })
  }
  emptyWards() {
    Taro.removeStorageSync('lastwardId');
    this.setState({
      statusType: 'empty',
      isVh100: true,
      statuserro: false,
    }, () => {
      this.setState({
        isShowPage: true,
      })
    })
  }
  initPage() {
    let userInfo = getGlobalData('userInfo') || utils.getUserInfo();
    let wardId = app.getValueSync('lastwardId') || (userInfo && userInfo.ward);
    if (userInfo === null) {
      app.wxLoginInit((state, msg, date) => {
        if (date && date.loginstatus === 0) {
          Taro.navigateTo({
            url: '/pages/login/index'
          })
        } else {
          this.initData(state, wardId);
        }
      })
    } else {
      app.checkRegister((state, msg, date) => {
        if (date && date.loginstatus === 0) {
          Taro.navigateTo({
            url: '/pages/login/index'
          })
        } else {
          this.initData(state, wardId);
        }
      });
    }
  }
  initData(state, wardId) {
    if (state === false) {
      this.setState({
        wardId,
        statusType: 'empty',
        statuserro: true
      })
    }
    this.setState({
      wardId
    }, () => {
      this.getAllwards();
    })
  }
  makePhoneCall(phone) {
    Taro.makePhoneCall({
      phoneNumber: phone,
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  }
  memuTap(e) { //点击按钮
    let { item } = e.currentTarget.dataset;
    if (item.name === '巡检') {
      let isFaist = false;
      isFaist = app.getValueSync('isFaist') || false;
      if (isFaist === false) {
        app.saveSync('isFaist', 1)
        item.path = '/pages/inspection/index'
      } else {
        this.setState({
          isScan: true
        }, () => {
          app.scan(() => {
            setTimeout(() => {
              this.setState({
                isScan: false,
                statusType: 'none',
              })
            }, 100)
          });
        })
        return;
      }
    }
    Taro.navigateTo({
      url: item.path
    })
  }
  getNewNoticeState() {
    let userInfo = getGlobalData('userInfo') || utils.getUserInfo();
    http.get('getNewNoticeState', {
      userid: userInfo.id
    }, false, false, false).then((res) => {
      this.setState({
        isNew: res.datas.isNew
      })
    }).catch((err) => {
      console.log(err)
    })
  }
  getMedicalkit(ward) {
    this.getNewNoticeState();
    http.get('getMedicalkitInfo', {
      wardid: ward
    }, false, false, false).then((d) => {
      this.setState({
        homeObj: d.datas,
        statusType: 'none',
        isVh100: true,
      })
    }).catch(() => {
      this.setState({
        homeObj: {
          countClass: 0,
          countAll: 0,
          countUse: 0,
          countValidity: 0
        },
        statusType: 'none',
        isVh100: true,
      })
      // this.setState({
      //   statusType: 'empty',
      //   statuserro: false,
      //   isVh100: false,
      // })
    })
  }
  onChange(e) {
    let { wardArr, wardId } = this.state;
    wardId = wardArr[e.detail.value].id
    app.saveSync('lastwardId', wardId);
    this.setState({
      wardId,
      wardObj: wardArr[e.detail.value]
    }, () => {
      this.getMedicalkit(wardId)
    })
  }
  render() {
    let { memuList, wardObj, phone, homeObj, statusType, statuserro, title, isVh100, isShowPage, wardArr, isNew } = this.state;
    return (
      <View className='home'>
        {isShowPage && <Block>
          <View className='pl-2-5 pr-2-5 pt-3 flex-item-center flex flex-c '>
            <View className='flex flex-r flex-item-between title-box'>
              <View>
                <AutoFormId renderCat={
                  <Picker mode='selector' disabled={wardArr.length > 1 ? false : true} range={wardArr} rangeKey='wardname' onChange={(event) => { this.onChange(event) }}>
                    <Text className='pr-2-5 ft_w600 ft46'>{wardObj.wardname}</Text>{wardArr.length > 1 && <Image className='more' src={require('../../assets/imgs/home/home_icon_pressed.png')}></Image>}
                  </Picker>
                }
                ></AutoFormId>
              </View>
              <View className='pl-2' onClick={() => {
                Taro.navigateTo({
                  url: '/pages/message/messageList/index'
                })
              }}
              >
                <AtBadge dot={isNew}>
                  <AutoFormId renderCat={
                    <View className='pr-1-5 pt-1' >
                      <Image className='remind' src={require('../../assets/imgs/home/home_icon_msg.png')}></Image>
                    </View>
                  }
                  ></AutoFormId>
                </AtBadge>
              </View>

            </View>
            {statusType === 'none' && <Block>
              <View className='medicine-cabinet mt-4-5 flex flex-c fc_FFF mb-3-5 bdr_10'>
                <View className='ft28 pt-4 pb-4 pl-3-5 pr-3-5 ft_w300'>今日药箱药品{homeObj.countClass}种，{homeObj.countAll}支，近效期药品{homeObj.countValidity}支</View>
                <View className='flex flex-r flex-1'>
                  <View className='flex-1 cabinet-info flex flex-item-v-center flex-c'
                    onClick={() => {
                      Taro.navigateTo({
                        url: '/pages/drugAdministration/index'
                      })
                    }}
                  >
                    <View className='mb-1-5'>
                      <AutoFormId renderCat={
                        <Text className='ft96 fc_FFF'>{homeObj.countAll - homeObj.countUse}<Text className='ft28'>/{homeObj.countAll}</Text></Text>
                      }
                      ></AutoFormId>
                    </View>
                    <Text className='ft24'>药品总数</Text>
                  </View>
                  <View className='flex-1 cabinet-info flex flex-item-v-center flex-c fc_F00' onClick={() => {
                    Taro.navigateTo({
                      url: '/pages/nearlyEffective/index'
                    })
                  }}
                  >
                    <AutoFormId renderCat={
                      <Text className='ft96 fc_F00'>{homeObj.countValidity}</Text>
                    }
                    ></AutoFormId>
                    <Text className='ft24 mt-1-5'>近期药品</Text>
                  </View>
                </View>
              </View>
              <View className='memu-list flex flex-r flex-warp bdr_10'>
                {
                  memuList.map(item => {
                    return (
                      <View onClick={this.memuTap} data-item={item} className='memu-item flex flex-c flex-item-center' key={item.name}>
                        <AutoFormId key={item.name} renderCat={
                          <View className='flex flex-c flex-item-center'>
                            <Image className='memu-item-img mb-3' mode='aspectFit' src={item.icon}></Image>
                            <Text className='ft28'>{item.name}</Text>
                          </View>
                        }
                        ></AutoFormId>
                      </View>
                    )
                  })
                }
              </View>
            </Block>}
          </View>
          {/* <View className={`footer-box line-t flex flex-item-between ft20 fc_999 ${getGlobalData('model') ? 'mb-6-5' : ''}`}>

            <View className='footer-btn flex-1 flex flex-item-center'>
              <AutoFormId renderCat={
                <View className='flex flex-c flex-item-center ft20 fc_999'>
                  <Image className='item-img' src={require('../../assets/imgs/home/home_icon_bzzx.png')}></Image>
                  <Text className='pt-1'>帮助中心</Text>
                </View>
              }
              ></AutoFormId>
            </View>
            <View onClick={() => { this.makePhoneCall(phone) }} className='footer-btn flex-1 flex flex-item-center'>
              <AutoFormId renderCat={
                <View className='flex flex-c flex-item-center ft20 fc_999'>
                  <Image className='active' src={require('../../assets/imgs/home/home_icon_lxyjk.png')}></Image>
                  <Text className='pt-1 mt-4'>联系药剂科</Text>
                </View>
              }
              ></AutoFormId>
            </View>
            <View onClick={() => { this.makePhoneCall(phone) }} className='footer-btn flex-1 flex flex-item-center'>
              <AutoFormId renderCat={
                <View className='flex flex-c flex-item-center ft20 fc_999'>
                  <Image className='item-img' src={require('../../assets/imgs/home/home_icon_jszc.png')}></Image>
                  <Text className='pt-1'>技术支持</Text>
                </View>
              }
              ></AutoFormId>
            </View>
          </View> */}
        </Block>}
        <StatusPages mt='mt-20'
          refresh={() => { utils.showLoading(), this.initPage() }}
          isVh100={isVh100}
          statusType={statusType}
          statuserro={statuserro}
          title={title}
        ></StatusPages>
      </View>
    )
  }
}

export default Index
